﻿module Sustainalytics.Controversies {

    export class ControversyIndicatorsController {

        private controversiesCtrl: ControversiesController;

        public controversyIndicators: ControversyIndicatorDto[] = [];
        public hasControversyIndicatorTabs: boolean = false;
        public selectedControversyIndicator: ControversyIndicatorDto = null;
        public relatedEventIndicators: EventIndicatorDto[] = [];
        public selectedEventIndicator: EventIndicatorDto = null;
        public eventIndicator: EventIndicatorDto = null;
        public selectedIncident: IncidentDto = null;
        public allIncidents: IncidentDto[] = null;
        public incidentGraph:IncidentDto[]=null;
        public incidents: IncidentDto[] = [];
        public isMainIncident: boolean = false;
        public incidentsSkip: number = 0;
        public incidentsTake: number = 0;
        public maxIncidentTake:number=3;
        public resetScrollPager: boolean = false;
        public scrollPagerLocked: boolean = true;

        public overallControversyLevel = null;

        public lastGetData: any;

        private userId: string;

        public notFound: boolean = false;
        public noClaims: boolean = false;


        public allTags:string="";

        //private goDefaultIncindent:boolean=true;

        constructor(
            private $scope: IThemeScope,
            private $rootScope: ng.IScope,
            private $location: ng.ILocationService, 
            private $anchorScroll: any, 
            private $q: ng.IQService,
            private $timeout: ng.ITimeoutService,
            private ControversiesService: IControversiesService,
            private staticObjects: Common.IStaticObjects
            
            ) {

            var ctx = this;

            if (ctx.$rootScope['userInfo'] == null) {
                ctx.$rootScope['userInfo'] = angular.fromJson(localStorage.getItem('sust_userInfo'));
            }
            ctx.userId = ctx.$rootScope['userInfo'].userId;

            ctx.incidentsTake = 0;
            ctx.controversiesCtrl = $scope['controversies'];
     
            $scope['controveryIndicators'] = ctx;
            //$rootScope['controversy_Indicators_controller'] = ctx;

            ctx.init();
        }

        private init(): ng.IPromise<any> {

            var ctx = this;

            ctx.scrollPagerLocked = true;

            var def = ctx.$q.defer();

            ctx.getControversyIndicators();


            // listen for scroll changes
            ctx.$scope.$watch('ciCtrl.incidentsSkip', onPageChange);
            ctx.$scope.$watch('ciCtrl.incidentsTake', onPageChange);

            // refresh on page changed
            function onPageChange() {
                
                if (!ctx.scrollPagerLocked) {
                    ctx.takeIncidents();
                }
            };

            return def.promise;
        }

        private getControversyIndicators(): ng.IPromise<any> {
            var ctx = this;

            if (!ctx.$scope.currentCompany || !ctx.$scope.currentTheme) {
                return ctx.$q.when(null);
            }

            var getData = {
                companyId: ctx.$scope.currentCompany.id,
                theme: ThemeEnum[ctx.$scope.currentTheme]
            };

            ctx.$rootScope['loading'] = true;

            var promise = ctx.ControversiesService.getControversyIndicators(getData.companyId, getData.theme);
            
            promise.then(
                function (cis) {
                   
                    ctx.$rootScope['loading'] = false;

                    // apply controversy indicators
                    ctx.controversyIndicators.push.apply(ctx.controversyIndicators, cis);

                    ctx.hasControversyIndicatorTabs = false;

                    for (var i = 0; i < ctx.controversyIndicators.length; i++) {
                        if (ctx.controversyIndicators[i].answerCategory > 0) {
                            ctx.hasControversyIndicatorTabs = true;
                        }
                    }

                    ctx.selectDefaultControversyIndicator();

                }, function (reason) {
                    console.log('Failed: ' + reason);

                    ctx.$rootScope['loading'] = false;

                    if (reason.status == 404 || reason.staus == 204) {

                        if (reason.data.errCode !== null) {
                            ctx.notFound =true;
                        }
                    }

                    if (reason.status == 401) {
                        ctx.noClaims = true;
                    }

                    ga('create', 'UA-4379897-6', {
                        'userId': ctx.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
                    });

                    ga('globalAccess.send', 'exception', { 'exDescription': 'Esg Ratings: Rp Indicators Controller -> Error retrieving indicators' });
                });

            return promise;
        }

        private selectDefaultControversyIndicator() {
            var ctx = this;

            ctx.selectedControversyIndicator = null;

            if (ctx.controversyIndicators && ctx.controversyIndicators.length > 0) {     

                if (ctx.controversiesCtrl.selectedControversyIndicator) {
                    for (var i = 0; i < ctx.controversyIndicators.length; i++) {
                        var controversyIndicator = ctx.controversyIndicators[i];
                        if (controversyIndicator.id == ctx.controversiesCtrl.selectedControversyIndicator.id) {

                            ctx.selectControversyIndicator(controversyIndicator);
                            ctx.controversiesCtrl.selectedControversyIndicator = null;

                            break;
                        }
                    }
                }
                else {
                    // use first controversy indicator as the default tab  
                    // ctx.selectControversyIndicator(ctx.controversyIndicators[0]);

                    for (var i = 0; i < ctx.controversyIndicators.length; i++) {
                        if (ctx.controversyIndicators[i].answerCategory > 0) {
                            ctx.selectControversyIndicator(ctx.controversyIndicators[i]);
                            break;
                        }
                    }
                }
            }
        }

        private selectControversyIndicator(controversyIndicator: ControversyIndicatorDto) {
            var ctx = this;

            ctx.selectedControversyIndicator = controversyIndicator;
            console.log('selected controversy indicator: ' + controversyIndicator.name);

            ctx.setRelatedEventIndicators(controversyIndicator);

            ctx.$location.hash("");
            console.log(ctx.$location.url());

            ctx.selectDefaultEventIndicator();
        }

        private selectDefaultEventIndicator() {
            var ctx = this;
         
            ctx.selectedEventIndicator = null;
            ctx.eventIndicator = null;

            if (ctx.selectedControversyIndicator.eventIndicators && ctx.selectedControversyIndicator.eventIndicators.length > 0) {
                if (ctx.controversiesCtrl.selectedEventIndicator) {
                    for (var i = 0; i < ctx.selectedControversyIndicator.eventIndicators.length; i++) {
                        var eventIndicator = ctx.selectedControversyIndicator.eventIndicators[i];

                        if (eventIndicator.id == ctx.controversiesCtrl.selectedEventIndicator.id) {

                            ctx.selectEventIndicator(eventIndicator);
                            ctx.controversiesCtrl.selectedEventIndicator = null;

                            break;
                        }
                    }
                }
                else {
                    // use first event indicator as the default tab
                    // ctx.selectEventIndicator(ctx.selectedControversyIndicator.eventIndicators[0]);
                    for (var i = 0; i < ctx.selectedControversyIndicator.eventIndicators.length; i++) {
                        var eventIndicator = ctx.selectedControversyIndicator.eventIndicators[i];
                        if (eventIndicator.answerCategory > 0) {
                            ctx.selectEventIndicator(eventIndicator);
                            break;
                        }
                    }
                                    
                }
            }
        }

        private selectEventIndicatorAndScroll(eventIndicator: EventIndicatorDto,scroll:boolean) {
            var ctx = this;
            //ctx.goDefaultIncindent = true;
            ctx.selectedEventIndicator = eventIndicator;
            console.log('selected event indicator: ' + eventIndicator.name);

            if (scroll) {
                ctx.$rootScope['is_controversy_navigation'] = true;
            }

            ctx.eventIndicator = null;
            ctx.allIncidents = null;
            ctx.incidentGraph = null;
            ctx.incidents = [];
            ctx.isMainIncident = false;

            ctx.scrollPagerLocked = true;
            ctx.incidentsTake = 0;
            ctx.notFound = false;
            ctx.$timeout(() => {
                ctx.$scope.$apply();
                ctx.scrollPagerLocked = false;
            });

            ctx.$location.hash("");
            console.log(ctx.$location.url());

            ctx.getEventIndicator().then(a => {
                ctx.$timeout(() => {
                    ctx.$scope.$apply(() => {
                        ctx.getIncidents(ctx.eventIndicator);
                    });
                });
            });
        }

        private selectEventIndicator(eventIndicator: EventIndicatorDto) {
            var ctx = this;
            ctx.selectEventIndicatorAndScroll(eventIndicator, false);

        }

        public selectIncident(incident: IncidentDto) {
            var ctx = this;

            ctx.selectedIncident = incident;
            console.log('selected incident: ' + ctx.selectedIncident.name);
            if (ctx.$rootScope['controversy_Indicators_controller']) {
                ctx.$rootScope['controversy_Indicators_controller'] = null;
            }
           
            ctx.takeIncidents();
        }

        private getRelatedEventIndicators(controversyIndicator: ControversyIndicatorDto): any {
            var ctx = this;

            var relatedEventIndicators: EventIndicatorDto[] = [];

            if (controversyIndicator.eventIndicators && controversyIndicator.eventIndicators.length > 0) {

                relatedEventIndicators = controversyIndicator.eventIndicators;
            }

            return relatedEventIndicators;
        }

        private setRelatedEventIndicators(controversyIndicator: ControversyIndicatorDto) {
            var ctx = this;

            ctx.overallControversyLevel = 0;
            ctx.relatedEventIndicators = [];

            if (controversyIndicator.eventIndicators) {

                ctx.relatedEventIndicators = controversyIndicator.eventIndicators;

                var categories = [];
                $.each(controversyIndicator.eventIndicators, function (index, eventIndicator) {
                    categories.push(eventIndicator.answerCategory);
                });
                categories.sort(function (a, b) { return a - b });
                ctx.overallControversyLevel = categories[categories.length - 1];
            }
        }

        private getEventIndicator(): ng.IPromise<any> {
            var ctx = this;

            if (!ctx.controversiesCtrl.company) {
                return ctx.$q.when(null);
            }

            if (!ctx.selectedEventIndicator) {
                return ctx.$q.when(null);
            }

            var companyId: string = ctx.$scope.currentCompany.id;
            var eventIndicatorId = ctx.selectedEventIndicator.id;

            var promise = ctx.ControversiesService.getEventIndicator(companyId, eventIndicatorId);

            promise.then(
                function (ei) {

                    ctx.$timeout(function () {
                        ctx.$scope.$apply(function () {
                            ctx.eventIndicator = ei;
                        });
                    });

                }, function (reason) {

                    console.log('Failed to get event indicator: ' + reason);

                    if (reason.status == 404 || reason.staus == 204) {

                        if (reason.data.errCode !== null) {
                            ctx.notFound = true;
                        }
                    }

                    if (reason.status == 401) {
                        ctx.noClaims = true;
                    }

                    ga('create', 'UA-4379897-6', {
                        'userId': ctx.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
                    });

                    ga('globalAccess.send', 'exception', { 'exDescription': 'Controversies: Event Indicator -> Error retrieving event indicator' });
                });

            return promise;
        }

        private getIncidents(eventIndicator: EventIndicatorDto): ng.IPromise<any> {
            var ctx = this;

            if (!ctx.controversiesCtrl.company) {
                return ctx.$q.when(null);
            }

            if (!eventIndicator) {
                return ctx.$q.when(null);
            }

            var companyId: string = ctx.$scope.currentCompany.id;


            var promise = ctx.ControversiesService.getIncidents(companyId, eventIndicator.id);

            promise.then(
                function (incidents) {

                    ctx.$timeout(function () {
                        ctx.$scope.$apply(function () {
                            ctx.allIncidents = incidents;
                            ctx.incidentGraph = [];
                            var arrTags = [];
                            for (var i = 0; i < incidents.length; i++) {
                                ctx.incidentGraph.push(incidents[i]);

                                if (incidents[i].isMainIncident) {
                                    ctx.isMainIncident = true;
                                }
                                if ($.inArray(incidents[i].mainTag, arrTags) == -1) arrTags.push(incidents[i].mainTag);
                            }
                            ctx.allTags = arrTags.join(',');


                            console.log('got ' + incidents.length + ' incidents');

                            if (ctx.$rootScope['incident_map_selected_summary']) {
                                ctx.selectedIncident = ctx.$rootScope['incident_map_selected_summary'];
                                ctx.$rootScope['incident_map_selected_summary'] = null;
                            }
                            if (ctx.$rootScope['incident_map_current_url']) {
                                console.log('Before '+ctx.$location.url());
                                ctx.$location.url(ctx.$rootScope['incident_map_current_url']);
                                ctx.$rootScope['incident_map_current_url'] = null;
                                console.log('After ' + ctx.$location.url());
                            }

                            ctx.takeIncidents();
                        });
                    });

                }, function (reason) {

                    console.log('Failed to get incidents: ' + reason);

                    if (reason.status == 404 || reason.staus == 204) {

                        if (reason.data.errCode !== null) {
                            ctx.notFound = true;
                        }
                    }

                    if (reason.status == 401) {
                        ctx.noClaims = true;
                    }

                    ga('create', 'UA-4379897-6', {
                        'userId': ctx.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
                    });

                    ga('globalAccess.send', 'exception', { 'exDescription': 'Controversies: Incidents -> Error retrieving event indicator' });
                });

            return promise;
        }
        private lastIncidentId: string;

        private takeIncidents() {
            var ctx = this;
            ctx.scrollPagerLocked = true;



            if (!ctx.allIncidents || ctx.allIncidents.length <= 0) {
                    return;
            }
            ctx.notFound = false;
            var take = 0;
            for (var i = ctx.incidentsTake; i < ctx.allIncidents.length; i++) {
                ctx.incidents.push(ctx.allIncidents[i]);
                take++;
                if (ctx.selectedIncident) {
                    if (ctx.allIncidents[i].id == ctx.selectedIncident.id) {
                        break;
                    }
                } else {
                    if (take >= ctx.maxIncidentTake) {
                        break;
                    }
                }
            }
            ctx.incidentsTake += take;
            
            if (ctx.incidentsTake >= ctx.allIncidents.length) {
                ctx.notFound = true;
            }

            if (ctx.controversiesCtrl && ctx.controversiesCtrl.selectedControversyIndicator) {
                ctx.controversiesCtrl.selectedControversyIndicator = null;
            }
            if (ctx.controversiesCtrl && ctx.controversiesCtrl.selectedEventIndicator) {
                ctx.controversiesCtrl.selectedEventIndicator = null;
            }

            if (ctx.$rootScope['is_controversy_navigation']) {
                ctx.$anchorScroll.yOffset = $("#top-wrap-scroll").height();
                ctx.$location.hash('scrollToDetail');
                ctx.$rootScope['is_controversy_navigation'] = false;
                //ctx.selectedIncident = ctx.allIncidents[ctx.incidentsTake-1];
                //console.log(ctx.selectedIncident);
                //ctx.goDefaultIncindent = false;
            }


            if (ctx.selectedIncident) {
                ctx.$anchorScroll.yOffset = $("#top-wrap-scroll").height();
                ctx.$location.hash(ctx.selectedIncident.id);
                console.log(ctx.$location.url());
                ctx.lastIncidentId = ctx.selectedIncident.id;
                ctx.selectedIncident = null;
            }

            ctx.$timeout(() => {
                ctx.$scope.$apply();
                ctx.scrollPagerLocked = false;
                if (ctx.$location.hash()=='' && ctx.controversiesCtrl) {

                    //ctx.$location.url(ctx.controversiesCtrl.currentUrl);
                    if (ctx.lastIncidentId) {
                        ctx.$location.hash(ctx.lastIncidentId);
                        ctx.lastIncidentId = null;
                    }
                }
                //ctx.$timeout(() => ctx.scrollPagerLocked = false, 100);
            },500);
        }

        private goToTop() {
            $("html, body").animate({
                scrollTop: $("#moduleLoaderProgress").prop("clientHeight") - 50
            }, 500);
        }
    }


    export var controversyIndicatorsControllerName = 'ControversyIndicatorsController'; 

    angular.module(controversiesModuleName).controller(controversyIndicatorsControllerName,
        ['$scope', '$rootScope', '$location', '$anchorScroll', '$q', '$timeout', 'ControversiesService', 'staticObjects', ControversyIndicatorsController]);
}